package com.mystudy.concurrent.myLock;

import java.util.ArrayList;
import java.util.Collection;

/**
 * TODO: 自定义锁实现类
 *
 * @author acy
 * @since 2019/05/15 15:22
 */
public class BooleanLock implements MyLock {

	//表示是否获取到了锁 ，true表示获取到了锁
	private boolean initValue;

	private Collection<Thread> blockedThreadCollection = new ArrayList<>();

	private Thread currentTread;

	public BooleanLock(boolean initValue) {
		this.initValue = initValue;
	}

	@Override
	public void lock() throws InterruptedException {
		//没有拿到所就放到阻塞集合种
		while (initValue) {
			blockedThreadCollection.add(Thread.currentThread());
			this.wait();
		}
		blockedThreadCollection.remove(Thread.currentThread());
		this.initValue = true;
		this.currentTread=Thread.currentThread();
	}

	@Override
	public void lock(long mills) throws InterruptedException, TimeOutException {

	}

	@Override
	public void unLock() {
		//只有当前线程才能释放锁
		if (Thread.currentThread()==currentTread){
			this.initValue = false;
			System.out.println(Thread.currentThread() + "从阻塞队列中移除");
			blockedThreadCollection.notifyAll();
		}
	}

	@Override
	public Collection<Thread> getBlockedThread() {
		return blockedThreadCollection;
	}

	@Override
	public int getBlockedSize() {
		return blockedThreadCollection.size();
	}
}
